package showtime.framework.manager
{
	import showtime.framework.core.pattern.Singleton;
	
	import flash.display.DisplayObject;
	import flash.events.KeyboardEvent;


	/**
	 * Keyboard manager.
	 * @author yinhao
	 * 
	 */
	public class KeyboardManager extends Singleton
	{
		private static var keyMap:Object = {};
		
		private static var _enabled:Boolean = false;
		
		public function KeyboardManager()
		{
			trace("[Keyboard Manager] - keyboard register complete.");
		}
		
		public static function registerRoot(root:DisplayObject):void
		{
			root.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			
			root.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			
			enabled();
		}
		
		public static function getInstance():KeyboardManager
		{
			return KeyboardManager(Singleton.getInstanceOrCreate(KeyboardManager));
		}
		/**
		 * Is down the key. 
		 * 
		 * @param keyCode
		 * @return 
		 * 
		 */		
		public function isDown(keyCode:int):Boolean
		{
			return keyMap[keyCode];
		}
		
		/**
		 * Key down handler. 
		 * @param evt
		 * 
		 */		
		private static function keyDownHandler(evt:KeyboardEvent):void
		{
			if (!_enabled)
			{
				return;
			}
			
			keyMap[evt.keyCode] = true;
		}
		
		/**
		 * Key up handler. 
		 * @param evt
		 * 
		 */		
		private static function keyUpHandler(evt:KeyboardEvent):void
		{
			delete keyMap[evt.keyCode];
		}
		
		public static function enabled():void
		{
			_enabled = true;
		}
		
		public static function disabled():void
		{
			_enabled = false;
		}
	}
}